from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from verifications.serializers import RegisterSMSAPIVIewSerializer

'''
图片验证码的实现
１　请求方式　get
２　由前端生成的ｕｕｉｄ　
３　接收ｕｕｉｄ　从第三方的库中拿到验证码图片和文本内容　用ｕｕｉｄ进行文本的拼接
４　拼接之后存到ｒｅｄｉｓ中　在返回图片的信息
'''


class RegisterImageAPIVIew(APIView):

    def get(self,request,image_code_id):

        from libs.captcha.captcha import captcha
        text,image = captcha.generate_captcha()

        from django_redis import get_redis_connection

        redis_conn = get_redis_connection('code')

        redis_conn.setex('image_%s'%image_code_id,300,text)

        return HttpResponse(image,content_type='image/jpeg')


# 访问方式： GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
'''
１　请求方式　get 　
２　请求参数　image_code_id 图片验证码内容　手机号正则校验
３　哪些需要校验　从ｒｅｄｉｓ中取出文本进行比较　　
４　校验通过后　需要通过第三方运通信进行短信内容的发送
５　发送短信内容的时候　需要自己生成短信验证码　保存到ｒｅｄｉｓ　库中　
６　这个时候用到了　异步发送短信逻辑　

'''


class RegisterSMSAPIVIew(APIView):

    def get(self,request,mobile):

        data = request.query_params

        serializer = RegisterSMSAPIVIewSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        from random import randint

        sms_code = '%06d'%randint(0,999999)
        print(sms_code)

        from django_redis import get_redis_connection

        redis_conn = get_redis_connection('code')

        redis_conn.setex('sms_code_%s'%mobile,300,sms_code)

        # from libs.yuntongxun.sms import CCP
        # ccp = CCP()
        #
        # ccp.send_template_sms('18694079593', [sms_code, 5], 1)

        from celery_tasks.sms.tasks import send_sms_code

        send_sms_code(mobile,sms_code)

        return Response({
            'sms':'ok'
        })